package com.emspost;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtils {

    // 加密算法
    private static final String ALGORITHM = "AES";

    // AES 加密
    public static String encrypt(String phoneNumber, String secretKey) throws Exception {
        // 使用密钥生成 AES 密钥对象
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipher.doFinal(phoneNumber.getBytes());
        // 将加密后的字节数组转换为 Base64 编码的字符串
        return Base64.getEncoder().encodeToString(encrypted);
    }

    // AES 解密
    public static String decrypt(String encryptedPhone, String secretKey) throws Exception {
        // 使用密钥生成 AES 密钥对象
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        // 对 Base64 编码后的密文进行解码
        byte[] decodedEncryptedPhone = Base64.getDecoder().decode(encryptedPhone);
        byte[] decrypted = cipher.doFinal(decodedEncryptedPhone);
        return new String(decrypted);
    }

    // 确保密钥长度为 16 字节
    private static byte[] getAESKey(String secretKey) {
        try {
            byte[] keyBytes = secretKey.getBytes();
            if (keyBytes.length < 16) {
                // 如果密钥小于 16 字节，使用 SHA-256 填充
                byte[] hash = java.security.MessageDigest.getInstance("SHA-256").digest(secretKey.getBytes());
                return java.util.Arrays.copyOf(hash, 16);  // 获取前 16 字节作为 AES 密钥
            } else if (keyBytes.length > 16) {
                // 如果密钥大于 16 字节，则裁剪为 16 字节
                return java.util.Arrays.copyOf(keyBytes, 16);
            }
            return keyBytes;
        } catch (Exception e) {
            throw new RuntimeException("Error in generating AES key", e);
        }
    }

    public static void main(String[] args) {
        try {
//            String phoneNumber = "18778763917";
            String phoneNumber = "18575035924";
            String secretKey = "e8fd54d774df407f"; // 密钥，长度小于 16 字节时会自动填充

            // 加密手机号
            String encryptedPhone = encrypt(phoneNumber, secretKey);
            System.out.println("Encrypted Phone: " + encryptedPhone);

//            encryptedPhone = "U2FsdGVkX1/w3ub8A8orHWKpOLAgqVNPUPWSq9ZOSMQ=";
            // 解密手机号
            String decryptedPhone = decrypt(encryptedPhone, secretKey);
            System.out.println("Decrypted Phone: " + decryptedPhone);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}